package com.wsoft.sms.interceptor;

import com.wsoft.sms.entity.SmsTemplateEntity;
import com.wsoft.sms.entity.SmsTemplateSendLogEntity;
import com.wsoft.sms.manager.TemplateManager;
import com.wsoft.sms.service.ISmsTemplateSendLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;


/**
 * @Author Zhang gukai
 * @Date 2024/12/31 15:47
 */
@Aspect
@Component
public class TemplateSendLogAspect {

    @Resource
    private TemplateManager templateManager;

    @Resource
    private ISmsTemplateSendLogService templateSendLogService;


    @Around("@annotation(com.wsoft.core.annotation.SmsLog)")
    public Object logSmsTemplateSend(ProceedingJoinPoint joinPoint) throws Throwable {

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        String templateCode = (String) args[0];
        String type = (String) args[1];
        String dataModelJson = (String) args[2];
        String to = (String) args[3];

        SmsTemplateEntity template = templateManager.getTemplateByCode(templateCode);
        // 创建日志对象
        SmsTemplateSendLogEntity log = new SmsTemplateSendLogEntity();
        log.setTitle(template.getTemplateName());
        log.setTemplateCode(templateCode);
        log.setType(type);
        log.setReceiver(to);
        log.setParam(dataModelJson);
        log.setTemplateContent(template.getTemplateContent());
        log.setSendTime(LocalDateTime.now());
        log.setSendStatus("0");

        try {
            // 执行目标方法
            Object result = joinPoint.proceed();

            // 记录推送成功
            log.setSendStatus("1");
            log.setContent(result.toString());
            log.setResult("推送成功");
            templateSendLogService.save(log);

            return result;
        } catch (Exception e) {
            // 记录推送失败
            log.setSendStatus("2");
            log.setResult("推送失败: " + e.getMessage());
            templateSendLogService.save(log);
            throw e;
        }
    }
}
